package gamewalletlogic

import (
	"context"
	"go.uber.org/zap"
	gameuserlogic "navi-mumbai/app/rpc/game/internal/logic/gameuser"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/third/game/wz"
	"strconv"

	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetGameWalletBalanceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetGameWalletBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetGameWalletBalanceLogic {
	return &GetGameWalletBalanceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询钱包余额
func (l *GetGameWalletBalanceLogic) GetGameWalletBalance(in *pb.GetGameWalletBalanceReq) (*pb.GetGameWalletBalanceResp, error) {
	defer utils.RecoverPanic()

	var rsp *pb.GetOpenIdByUidResp
	var err error
	rsp, err = gameuserlogic.NewGetOpenIdByUidLogic(l.ctx, l.svcCtx).GetOpenIdByUid(&pb.GetOpenIdByUidReq{
		Uid:        in.Uid,
		ProviderId: in.ProviderId,
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	wzReq := wz.BalanceReq{
		Uid:      strconv.FormatInt(rsp.OpenId, 10),
		Currency: walletkey.GetGameCurrency(in.ProviderId, in.MoneyType),
		User:     rsp.Nickname,
	}
	l.Logger.Info("GetGameWalletBalance", "wzReq", wzReq)
	var wzResp *wz.BalanceResp
	wzResp, err = wz.Hc.Balance(&wzReq)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	resp := pb.GetGameWalletBalanceResp{
		Balance:   wzResp.Data.Balance,
		MoneyType: walletkey.GetMoneyTypeFromGame(in.ProviderId, wzResp.Data.Currency),
	}
	return &resp, nil
}
